package com.bioscript.standalone.IO;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import com.bioscript.standalone.IO.HitsParsingEvents.HitsParsingEventTypes;
import com.bioscript.standalone.IO.baseClasses.BaseListener;
import com.bioscript.standalone.IO.baseClasses.BaseEvent.BaseEventTypes;

public class HitsFileParser<E> extends BaseListener<HitsParsingEvents> {
	
	private E value = null;
	
	public E getValue()
	{
		return value;
	}
	
	public void setValue(E obj)
	{
		this.value = obj;
	}
	
	private List<BaseListener<HitsParsingEvents>> eventListeners = 
		new LinkedList<BaseListener<HitsParsingEvents>>();
	
	public void addListener(BaseListener<HitsParsingEvents> hitsParsingListener)
	{
		eventListeners.add(hitsParsingListener);
	}
	
	private void fireEvent(HitsParsingEvents parseEvent)
	{
		for (BaseListener<HitsParsingEvents> listener : eventListeners)
		{
			listener.handleEvent(parseEvent);
		}
	}
	
	public void parse(FileReader fileReader) throws IOException
	{
		addListener(this);
		BufferedReader bufferedReader = new BufferedReader(fileReader);
		fireEvent(new HitsParsingEvents(null,BaseEventTypes.docStarted));
		String readLine = bufferedReader.readLine();
		while(readLine != null)
		{
			readLine = readLine.trim();
			if (readLine.startsWith("#"))
			{
				fireEvent(new HitsParsingEvents(readLine, HitsParsingEventTypes.comment));
			}
			else 
			{
				fireEvent(new HitsParsingEvents(readLine, HitsParsingEventTypes.entry));
			}
			readLine = bufferedReader.readLine();
		}
		fireEvent(new HitsParsingEvents(null,BaseEventTypes.docEnded));
	}

	@Override
	public void handleEvent(HitsParsingEvents event) {
		System.err.println("One should override the method handleEvent");
		System.exit(-1);
	}
}
